<?php

    if (!defined('BASEPATH'))
        exit('No direct script access allowed');

    /*
     * Glavna klasa - controler - komunicira sa servisima
     */

    class Main extends CI_Controller {

        public function __construct() {
            parent::__construct();

            // Load the rest client spark
            $this->load->spark('restclient/2.1.0');

            $this->rest->initialize(array(
                'server' => REST_URL_HOTELS,
                'http_user' => 'online',
                'http_pass' => 'booking',
                'http_auth' => 'basic' // or 'digest' 
            ));

            $this->activeLang = $this->lang->mci_current();

            require_once './application/libraries/urlify.php';

            $this->load->driver('cache', array('adapter' => 'file')); // za uklucuvanje na kes mogucnosti
            // CMS Assets
            $this->load->helper('gallery');
            $this->load->model('cms');
            $this->load->library('factory');
            $this->translate = $this->factory->create('translate');
        }

        public function index() {
            $this->home();
        }

        /*
         * Home page
         * 
         * @params : 
         *      input ('popular', 'visited', 'specialHotels', 'specialDests', 'recommended', 'googlemap','recentlybooked', 'allDests')
         */

        public function home() {

            $home_page = array('recommended', 'specialHotels', 'popular', 'visited', 'googlemap', 'allDests');

            $file = cache_filename(array('lang' => $this->activeLang), 'combined');

            if (!$combined = $this->cache->get($file)) {

                $combined = $this->rest->post(
                        'home', array('lang' => $this->activeLang, 'input' => $home_page));

                if (DO_CACHE)
                    $this->cache->save($file, $combined, 300);
            }

            foreach ($home_page as $key)    // copy results to $data
                $data[$key] = $combined->{$key};

            if (isset($data['googlemap']))  // parse array of objects with coordinates
                $data['googlemap'] = make_google_map($data['googlemap']);

            $data = currency_convert($data);    // Convert currency

            $this->_load_things_CMS($data, 'top_beaches', 48);
            $this->_load_things_CMS($data, 'national_parks', 55);
            $this->_load_things_CMS($data, 'canyons', 61);

//            $this->firephp->log($data);

            $this->template->load('site/home', $data);
        }

        /*
         * Autocomplete
         * 
         * @params : 
         *      name_startsWith
         *      plus_hotels
         * 
         */

        public function destinations_hotels_JSON($plus_hotels = FALSE) {

            $rest_data = array(
                "name_startsWith" => $_GET['name_startsWith'],
                "plus_hotels" => $plus_hotels,
                "lang" => $this->activeLang
            );

            $file = cache_filename($rest_data, 'combined');

            if (!$items = $this->cache->get($file)) {

                $items = $this->rest->post("destinationsHotelsAutocomplete", $rest_data);

                if (DO_CACHE)
                    $this->cache->save($file, $items, 300);
            }

            // parse each row to regular array
            if ($plus_hotels):
                $myItems = array();
                foreach ($items as $value)
                    $myItems[] = get_object_vars($value);       // convert STD to Array




                    
//trip whitespace
                $cnt = count($myItems);
                for ($index = 0; $index < $cnt; $index++) :
                    $myItems[$index]['name'] = trim($myItems[$index]['name']);
                    $myItems[$index]['label'] = trim($myItems[$index]['label']);

                endfor;

                // sort
                sort_array_of_array($myItems, 'name', TRUE);
                $items = $myItems;
            endif;

            //echo JSON to page  
            $response = $_GET["callback"] . "(" . json_encode(array('items' => $items)) . ")";
            echo $response;
        }

        /*
         * Search page
         * 
         * @params:
         *      check_in
         *      check_out
         *      nr_adults
         *      ages
         *      dest_hot
         * 
         */

        public function search() {
            
            
            $home_page = array('recommended', 'specialHotels', 'popular', 'visited', 'googlemap', 'allDests');

            $file = cache_filename(array('lang' => $this->activeLang), 'combined');

            if (!$combined = $this->cache->get($file)) {

                $combined = $this->rest->post(
                        'home', array('lang' => $this->activeLang, 'input' => $home_page));

                if (DO_CACHE)
                    $this->cache->save($file, $combined, 300);
            }

            foreach ($home_page as $key)    // copy results to $data
                $data[$key] = $combined->{$key};

            if (isset($_GET['preview']))
                $rest_method = 'searchPreview';
            else
                $rest_method = 'search';

            $file = cache_filename($_GET, 'results');
            //
            if (!$data['results'] = $this->cache->get($file)) {

                $data['results'] = $this->rest->post($rest_method, $_GET);

                if (DO_CACHE)
                    $this->cache->save($file, $data['results'], 300);
            }
            //            $this->firephp->log($_GET);
            //            $this->firephp->log($data['results']);
            if (isset($_GET['acc_type']))
                filter_acc_type($data['results'], $_GET['acc_type']);

            loadJoinedGroupsAttributes($data['results']);
            
            $items = $rest_method == 'search' ? make_sort_price_available($data['results']) : $data['results'];
            $data['items'] = json_encode($items);
            
            $data['unique'] = findUniqueMakeCount($data['results']); // find unique filter attributes
            $data['unique_prices'] = findUniquePricesMakeCount($data['results'], isset($_GET['preview'])); // find unique prices for filter
            $data['unique_stars'] = findUniqueStarsMakeCount($data['results']); // find unique stars for filter
            // sort, splice and shuffle facilities & services
            sort_attributes($data['unique']);
            if (count($data['unique']) > 23)
                array_splice($data['unique'], 23);

            shuffle($data['unique']);

            // sort stars array
            ksort($data['unique_stars']);

            // load objects for maps
            $data['googlemap'] = make_google_map($data['results']);

            $data = currency_convert($data);    // Convert currency
//            $this->load->helper('search_seo');
//            $data['seo_title'] = search_title();
//            $data['seo_description'] = search_description();
//            $data['seo_keywords'] = lang('keywords-home');
//            $data['h1_title'] = search_h1();
//            $this->firephp->log($data);


            $file = cache_filename(array('lang' => $this->activeLang), 'combined');

            if (!$combined = $this->cache->get($file)) {

                $combined = $this->rest->post(
                        'home', array('lang' => $this->activeLang, 'input' => $home_page));

                if (DO_CACHE)
                    $this->cache->save($file, $combined, 300);
            }
            $data['allDests'] = $combined->allDests;
            
            $this->template->load('site/results', $data);
        }

        /*
         * Object details with rooms and prices
         * 
         * @params:
         *      check_in
         *      check_out
         *      nr_adults
         *      ages
         *      hotel_id
         * 
         */

        public function accommodation($i) {

            if (isset($_GET['preview']))
                $rest_method = 'detailsPreview';
            else
                $rest_method = 'details';

            $id = explode('-', $i);
            $ide = $id[count($id) - 1];

            $_GET['hotel_id'] = $ide;

            $data['details'] = $this->rest->post($rest_method, $_GET);

            $this->firephp->log($data);

            $this->template->load('site/accommodation', $data);
        }

        /*
         * Subscribe
         */

        public function subscribe() {

            $answer = $this->rest->post("subscribe", $_GET);

            echo json_encode($answer);
        }

        private function _load_things_CMS(&$data, $index, $ID) {



            $data[$index] = $this->translate->res_array($this->cms->all_posts($ID), $this->activeLang);
            $data[$index . '_files'] = $this->cms->get_files($ID);
        }

    }

?>
